<?php

/**
 * Modelo de datos para usuarios ACL del admin
 *
 * @category Zwei
 * @package Models
 * @version $Id:$
 * @since 0.1
 *
 */

class AclUsersModel extends Zwei_Db_TableLoggeable
{
    protected $_name = "acl_users";
    protected $_name_roles = "acl_roles";
    protected $_name_persona = "persona";
    protected $_generate_pass = "user_name";
    protected $_data_persona = array();

    public function select()
    {
    	$this->setAdapter("auth");
        $select = new Zend_Db_Table_Select($this);
        $select->setIntegrityCheck(false); //de lo contrario no podemos hacer JOIN
        $select->from($this->_name)
        ->joinLeft($this->_name_persona, "$this->_name.id = $this->_name_persona.USER_ID")
        ->joinLeft($this->_name_roles, "$this->_name.acl_roles_id = $this->_name_roles.id", "role_name");

        //Si no pertenece al role_id 1, no puede ver a otros usuarios con ese perfil
        if ($this->_user_info->acl_roles_id != '1') {
            $select->where('acl_roles_id <> ?', '1');
        }
        
        return $select;
    }

    
    private function cleanDataParams($data)
    {
    	$this->_data_persona["NOMBRES"] = $data["NOMBRES"];
        unset($data["NOMBRES"]);
        $this->_data_persona["APELLIDO_P"] = $data["APELLIDO_P"];
        unset($data["APELLIDO_P"]);
        $this->_data_persona["APELLIDO_M"] = $data["APELLIDO_M"];
        unset($data["APELLIDO_M"]);
        $this->_data_persona["EMAIL"] = $data["EMAIL"];
        unset($data["EMAIL"]);
    	return $data;
    }
    
    
    /**
     * En el caso de crearse un usuario nuevo,
     * se genera la password repitiendo el nombre de usuario en md5
     * @return int
     */
    public function insert($data)
    {
    	$this->setAdapter("an");
        $data = $this->cleanDataParams($data);
        $data["password"] = md5($data[$this->_generate_pass]);
        try {
            $last_insert_id = parent::insert($data);
            if (is_object($this->getAdapter()->getProfiler()->getLastQueryProfile())) {
                $query = $this->getAdapter()->getProfiler()->getLastQueryProfile()->getQuery();
                $query_params = print_r($this->getAdapter()->getProfiler()->getLastQueryProfile()->getQueryParams(),true);
                $this->getAdapter()->getProfiler()->setEnabled(false);
                Zwei_Utils_Debug::write("[TRANSACTION:{$this->_form->action}]\nUser:{$this->_user_info->user_name}\nQuery:$query\nQuery Params:$query_params",  "../log/transactions");
            } else {
                $log_data = print_r($data, true);
                Zwei_Utils_Debug::write("Se modificó {$this->_name} TRANSACTION:{$this->_form->action} \nUser:{$this->_user_info->user_name} \nData:$log_data", "../log/transactions");
            }
            
        } catch(Zend_Db_Exception $e) {
            if ($e->getCode() == '23000') {
                $this->setMessage('Nombre de Usuario en uso.');
                return false;
            } else {
                Zwei_Utils_Debug::write("error:".$e->getMessage()."code".$e->getCode());
            }
        }
        
        $persona = new PersonaModel();
        
        $this->_data_persona["USER_ID"] = $last_insert_id;
        
        
        try {
            $insertOrUpdate = $persona->insert($this->_data_persona);
        } catch (Zend_Db_Exception $e) {
        	Zwei_Utils_Debug::write($e->getMessage()." ".$e->getCode());
        	Zwei_Utils_Debug::write($this->_data_persona);
        	unset($this->_data_persona["USER_ID"]);
        	$where = $this->getAdapter()->quoteInto("USER_ID = ?", $last_insert_id);
        	$insertOrUpdate = $persona->update($data, $where);
        }    

        if (!$last_insert_id && $insertOrUpdate) $last_insert_id = $insertOrUpdate;
        return $last_insert_id;
    }

    /**
     * Captura de excepciones posibles como nombre de usuario en uso
     * @param  array        $data  Column-value pairs.
     * @param  array|string $where An SQL WHERE clause, or an array of SQL WHERE clauses.
     * @return int          The number of rows updated.
     */

    public function update($data, $where)
    {
    	$this->setAdapter("an");
        $data = $this->cleanDataParams($data);

        try {
            $update = parent::update($data, $where);
            
            if (is_object($this->getAdapter()->getProfiler()->getLastQueryProfile())) {
                $query = $this->getAdapter()->getProfiler()->getLastQueryProfile()->getQuery();
                $query_params = print_r($this->getAdapter()->getProfiler()->getLastQueryProfile()->getQueryParams(),true);
                $this->getAdapter()->getProfiler()->setEnabled(false);
                Zwei_Utils_Debug::write("[TRANSACTION:{$this->_form->action}]\nUser:{$this->_user_info->user_name}\nQuery:$query\nQuery Params:$query_params",  "../log/transactions");
            } else {
                $log_data = print_r($data, true);
                $log_where = print_r($where, true);
                Zwei_Utils_Debug::write("Se modificó {$this->_name} TRANSACTION:update \nUser:{$this->_user_info->user_name} \nData:$log_data \nWhere:$log_where", "../log/transactions");
            }
        } catch(Zend_Db_Exception $e) {
            if ($e->getCode() == '23000') {
                $this->setMessage('Nombre de Usuario en uso.');
                return false;
            } else {
                Zwei_Utils_Debug::write("error:".$e->getMessage()."code".$e->getCode());
            }
        }
        
        $persona = new PersonaModel();
        $array = $this->whereToArray($where);
        $USER_ID = str_replace("'", "", $array[1]);
        $this->_data_persona["USER_ID"] = $USER_ID;        
        try {
            $insertOrUpdate = $persona->insert($this->_data_persona);
        } catch (Zend_Db_Exception $e) {
            if ($e->getCode() != 23000) Zwei_Utils_Debug::write($e->getMessage()." ".$e->getCode());
            $where = $this->getAdapter()->quoteInto("USER_ID = ?", $USER_ID);
            unset($this->_data_persona["USER_ID"]);
            $insertOrUpdate = $persona->update($this->_data_persona, $where);
        }    
        
        $this->getAdapter()->getProfiler()->setEnabled(false);
        if (!$update && $insertOrUpdate) $update = $insertOrUpdate;
        
        return $update;
    }
}
